package com.by.datasource.handler;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.by.toolkit.consts.DatePatternConst;
import com.by.toolkit.consts.GlobalConst;
import com.by.toolkit.platform.ByContext;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 数据库自动填充
 *
 * @author YanBingHao
 * @since 2023/12/25
 */
public class ByMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        long currentTimeMillis = System.currentTimeMillis();
        this.setFieldValByName("createTimeLong", currentTimeMillis / 1000, metaObject);
        this.setFieldValByName("updateTimeLong", currentTimeMillis / 1000, metaObject);
        this.setFieldValByName("createTime", now, metaObject);
        this.setFieldValByName("updateTime", now, metaObject);
        this.setFieldValByName("createDate", Long.parseLong(LocalDateTimeUtil.format(LocalDate.now(), DatePatternConst.DATE_STAMP)), metaObject);
        this.setFieldValByName("updateDate", Long.parseLong(LocalDateTimeUtil.format(LocalDate.now(), DatePatternConst.DATE_STAMP)), metaObject);
        this.setFieldValByName("operatorUserId", Optional.ofNullable(ByContext.getOperationUserId()).orElse(GlobalConst.NEGATIVE_ONE_LONG), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        long currentTimeMillis = System.currentTimeMillis();
        this.setFieldValByName("updateTime", now, metaObject);
        this.setFieldValByName("updateDate", Long.parseLong(LocalDateTimeUtil.format(LocalDate.now(), DatePatternConst.DATE_STAMP)), metaObject);
        this.setFieldValByName("updateTimeLong", currentTimeMillis / 1000, metaObject);
        this.setFieldValByName("operatorUserId", Optional.ofNullable(ByContext.getOperationUserId()).orElse(GlobalConst.NEGATIVE_ONE_LONG), metaObject);
    }
}
